﻿// <copyright file="PuzzleManager.cs" company="ThorIndustry">Copyright (c) ThorIndustry. All rights reserved.</copyright>

using System.Collections.Generic;

public class PuzzleManager : IPuzzleService
{
    private Dictionary<string, PuzzleShape[]> shapeByDefinition = new Dictionary<string, PuzzleShape[]>();

    public Puzzle CurrentPuzzle
    {
        get;
        private set;
    }

    public void Initialize()
    {
        UnityEngine.Debug.Log("PuzzleManager Initialize.");
        
        // Load available puzzle.
        // Sort them.
        Services.Register<IPuzzleService>(this);
    }

    public PuzzleDefinition[] GetPuzzleDefinitions()
    {
        IDatatableService datatableService = Services.GetService<IDatatableService>();
        IDatatable<PuzzleDefinition> puzzleDefinitionDatabase = datatableService.GetDatatable<PuzzleDefinition>();

        return puzzleDefinitionDatabase.GetValues();
    }

    public Puzzle SelectPuzzle(string puzzleDefinitionName)
    {
        IDatatableService datatableService = Services.GetService<IDatatableService>();
        IDatatable<PuzzleDefinition> puzzleDefinitionDatabase = datatableService.GetDatatable<PuzzleDefinition>();

        PuzzleDefinition puzzleDefinition;
        if (puzzleDefinitionDatabase.TryGetValue(puzzleDefinitionName, out puzzleDefinition))
        {
            Puzzle puzzle = new Puzzle();
            puzzle.Initialize(puzzleDefinition);

            this.CurrentPuzzle = puzzle;

            return puzzle;
        }

        return null;
    }

    public PuzzleShape[] GetPuzzleShapesByPuzzleShapeDefinitionName(string shapeDefinitionName)
    {
        // As the shape can be reuse from one puzzle to another, try to not waste memory...
        if (!this.shapeByDefinition.ContainsKey(shapeDefinitionName))
        {
            IDatatableService datatableService = Services.GetService<IDatatableService>();
            IDatatable<ShapesDefinition> shapesDefinitionDatabase = datatableService.GetDatatable<ShapesDefinition>();

            ShapesDefinition loculusShapeDefinition = shapesDefinitionDatabase.GetValue(shapeDefinitionName);
            if (loculusShapeDefinition == null)
            {
                UnityEngine.Debug.Log("No shape definition with name " + shapeDefinitionName);
            }

            PuzzleShape[] shapes = new PuzzleShape[loculusShapeDefinition.Polygons.Length];
            for (int index = 0; index < shapes.Length; ++index)
            {
                shapes[index] = new PuzzleShape(loculusShapeDefinition.Polygons[index]);
                shapes[index].Initialize();
            }

            this.shapeByDefinition.Add(loculusShapeDefinition.Name, shapes);
        }

        return this.shapeByDefinition[shapeDefinitionName];
    }
}
